<template lang="pug">
  .container
    s-table(
      ref="table"
      v-if="$route.path === '/teacherResource/manage'"
      reqUrl="/api/staff_extend/info/list_join"
      reqMethod="get"
      :column="tableObj.column"
      :selection="false"
      :filterProps="{fields: tableObj.filterItems}"
      :queryPropsParams="{areaId: curArea.areaId, deleted: false}"
      :callback="getDataCallback"
      @selection-change="handleSelectionChange"
    )
      .table-operator(slot="table-operator")
        <!--el-button(size="large" round :disabled="selectedRows.length < 1" @click="deleteHandle()") 删除-->
        <!--el-button(size="large" round :disabled="selectedRows.length < 1" @click="exportHandle()") 导出-->
        <!--upload-file(-->
          <!--style="display: inline-block;margin-right: 10px"-->
          <!--actionUrl="/api/crm/web/leads/importLeadsExcel"-->
          <!--name="files"-->
          <!--accept=".xlsx,.xls"-->
          <!--:show-file-list="false"-->
          <!--:headers="{ticket}"-->
          <!--@change="importChange"-->
        <!--)-->
          <!--el-button.ml10(size="large" round plain) 导入-->
        el-button.gradientVertical(size="large" round @click="addHandle()") 新增
      template(slot="gender" slot-scope="text, scope") {{dictFilter(text, 'sex')}}
      template(slot="joinAt" slot-scope="text, scope") {{text | dateFilter('YYYY/MM/DD')}}
      template(slot="status" slot-scope="text, scope") {{text === 1 ? '离职' : '正常'}}
      template(slot="rankVal" slot-scope="text, scope")
        el-rate(:value="text | rankValFilter" disabled)
      template(slot="action" slot-scope="text, scope")
        el-link(@click="detailHandle(scope.id)" type="success") 查看
        el-link(v-if="scope.status !== 1" @click="scoreHandle(scope)") 打分
        el-link(v-if="scope.status !== 1" @click="roleHandle(scope)" type="primary") 角色
        el-popconfirm(
            :title="`此操作将员工${scope.status === 1 ? '入职' : '离职'}, 是否继续??`"
            @confirm="() => onToggleClass(scope)"
            @onConfirm="() => onToggleClass(scope)"
          )
          el-link(
            slot="reference"
            :type="scope.status === 1 ? 'primary' : 'info'"
          )
            | {{scope.status === 1 ? '入职' : '离职'}}
    router-view(v-else)
    add-drawer(:visible.sync="addObj.visible" :id="addObj.id" @getList="() => refreshTable(true)")
    score-drawer(:visible.sync="scoreObj.visible" :id="scoreObj.id" :info="scoreObj.info" @getList="() => refreshTable(true)")
    add-drawer-base(:visible.sync="addObjBase.visible" :id="addObjBase.id" @getList="() => refreshTable(true)")
    modal-form(
      title="角色设置"
      :visible.sync="roleObj.visible"
      :fields="roleField"
      :submitHandle="addSubmit"
      :submitting="addSubmitting"
      :layoutCol="{ sm: 24, md: 24, lg: 24 }"
    )
</template>
<script>
import { mapGetters } from 'vuex'
import { dictMixin } from '@/mixins'
import { getToken } from '@/utils/auth'
import { seachConfig, columnConfig } from './config'
import AddDrawer from '../components/add'
import AddDrawerBase from '../components/addBase'
import ScoreDrawer from '../components/score'
import { submitStaff, staffQuit, setStaffRoles, staffEntry } from '../api'
import { getRoleTypes } from '@/api/common'

export default {
  components: {
    AddDrawer,
    ScoreDrawer,
    AddDrawerBase
  },
  filters: {
    rankValFilter (val) {
      return parseInt(val)
    }
  },
  mixins: [dictMixin],
  data () {
    return {
      ticket: getToken(),
      searchParameter: {},
      tableObj: {
        column: columnConfig,
        filterItems: seachConfig
      },
      addObj: {
        visible: false,
        id: ''
      },
      scoreObj: {
        visible: false,
        id: '',
        info: {}
      },
      addObjBase: {
        visible: false,
        id: ''
      },
      roleObj: {
        visible: false
      },
      addSubmitting: false,

      selectedRows: [],
      positionNumList: [],

      roleList: []
    }
  },
  computed: {
    ...mapGetters(['curArea']),

    roleField () {
      return [
        {
          key: 'role',
          type: 'select',
          label: '角色选择',
          fieldProps: {
            options: this.roleList,
            props: { value: 'roleId', label: 'roleName' },
            multiple: true
          }
        }
      ]
    }
  },
  mounted () {
    this.getRole()
  },
  methods: {
    refreshTable (flag = false) {
      this.$refs.table.refresh(flag)
    },
    // 请求数据包装返回
    getDataCallback ({ res, parameter }) {
      this.searchParameter = parameter
      this.positionNumList = res.positionNumList || []
      return res.page
    },
    handleSelectionChange (rows) {
      this.selectedRows = rows
    },
    addHandle (id = '') {
      this.addObjBase = {
        visible: true,
        id
      }
    },
    detailHandle (id) {
      this.$router.push({
        path: '/teacherResource/manage/info',
        query: {
          id
        }
      })
    },
    scoreHandle (info = {}) {
      this.scoreObj = {
        id: info.id,
        info,
        visible: true
      }
    },
    importChange () {},
    deleteHandle () {
      const { selectedRows } = this
      submitStaff({}, { ids: selectedRows.map(x => x.id).join('|') }, 'delete').then(() => {
        this.$message.success('删除成功')
        this.refreshTable()
      })
    },
    exportHandle () {},

    onToggleClass (row) {
      if (row.status === 1) {
        this.entryHandle(row)
      } else {
        this.quitHandle(row)
      }
    },
    quitHandle (row) {
      staffQuit({ staffId: row.id }).then(res => {
        this.refreshTable()
      })
    },

    entryHandle (row) {
      console.log('entryHandle')
      staffEntry({ staffId: row.id }).then(res => {
        this.refreshTable()
      })
    },

    randomNum (Min, Max) {
      const Range = Max - Min
      const Rand = Math.random()
      return (Min + Math.round(Rand * Range))
    },
    roleHandle (row) {
      console.log(row)
      this.roleObj = {
        visible: true,
        id: row.id
      }
    },
    addSubmit (res) {
      console.log(res)
      const { id: staffId } = this.roleObj

      const roleIds = res.role.map(x => x)
      setStaffRoles({
        staffId: staffId,
        roleIds: roleIds.join()
      }).then(res => {
        console.log(res)
        this.$message.success('设置成功')
        this.roleObj = {
          visible: false
        }
        this.refreshTable()
      })
    },

    getRole () {
      getRoleTypes().then(res => {
        console.log(res)
        this.roleList = res
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.container{
  padding: 30px;
  background: #FFFFFF;
}
.el-link.el-link--default{
  color: #409EFF !important;
}
</style>
